/**
 * @author {Yuntao Zhou}
 */
if (!Util){
    var Util = {};
}
Util.MultiDataGrid=function(container,data,oConfig,callback){
    var self=this;
    this.el=null;
    this.container = $(container);
    this.data=null;
    this.width=null;
    this.height=null;
    this.gColumn=null;
    this.gWidth=null;
    this.config={
        width:600,
        height:400,
		fixHeight:true,
        gRowsHeight:21, 
        columnSeparate:false,
        groupTitleRows:1,
        groupAutoSort: false,
        gConfig:{
            cellResize:false,
            groupDragable:false,
            groupDropable:false
        },
        gColumns:[]
    };
    $.extend(true,this.config,oConfig); 
    this.cb={
        onRowDoubleClick:null,
        onRowContextmenu:null,
        onRowRemove:null,
        onRowDragStart:null,  //e, proxy, row;
        onRowRearrange:null,  //function(Row, insertBeforeRow){}
        onRowSelected:null,  //function(e, Row){}
        onCellSort:null,
        onCellRearrange:null,  //function(cellKey, order){}
        beforeGroupDrop:null,
        afterRebindData:null,//function(){}
        onScrollEnd:null   //function(scrollLeft, scrollTop){}
    };
    $.extend(this.cb, callback);
    this._callbackCount={
        'cellsort':0,
        'cellrearrange':0,
        'rowdoubleclick':0
    };
    this.grids=[];
    this.gridHeads=[];
    this.hideGrids=[];
    this.hideGridHeads=[];
    this.body=null;
    this.head=null;
    this.DOMMap={};
	this.rows={};
    this.scrollPanel=null;
    this.gIndexMap={};//the grid index map of the group
    this.maxAddRowsNum=null;
    this.groupSequence=null;
    this.data=null;
    this.groupIndexMap=null;
    this.groups=[];
	this._id=0;
    this.HTML='<div class="rtq-multi-grid"><div class="rtq-multi-grid-hd rtq-grid"></div><div class="rtq-multi-grid-scroll"><div class="rtq-multi-grid-bd"></div></div></div>';
    this.init(data);
};
Util.MultiDataGrid.prototype={
    init:function(data){
        var self=this;
        this.el=$(this.HTML);
        this.el.appendTo(this.container);
        this.body=this.el.find('.rtq-multi-grid-bd');
        this.head=this.el.find('.rtq-multi-grid-hd');
		if (this.config.fixHeight) {
			this.scrollPanel = new Util.ScrollPanel(this.el.find('.rtq-multi-grid-scroll'), {}, {
				onScroll: function(l, t){
					if (self.gridHeads.length > 0) {
						self.gridHeads[0].el.parent().scrollLeft(l);
					}
				},
				onScrollEnd: function(l, t){
					self._trigger('scrollend', [l, t]);
				}
			});
		}
        var w=this.config.width;
        var h=this.config.height-this.head.height();    
        this._createMultiGrid(w, h, this.config.gColumns);
        if(data&&data.length>0){
            this.reBindData(data);
        }
    },
    _setGridWidth:function(cols){
        this.gWidth=0; 
        for(var i=0;i<cols.length;i++){
            this.gWidth+=2;
            if (!cols[i].hide){
                this.gWidth +=parseInt(cols[i].width) || 80;
            }
        }
    },
    _createMultiGrid:function(w,h,cols){        
        if(w>0){
            this.body.width(w);
        }
        if(h>0){
			if (this.config.fixHeight) {
				this.body.height(h);
			}
            this.maxAddRowsNum=parseInt(h/this.config.gRowsHeight,10)-1;
        }
        this.grids=[];
        this.gridHeads=[];
        this.head.empty();
        this.body.empty();
        this._setGridWidth(this.config.gColumns);
        var gEl,ghEl,num;   
        num=parseInt(w/(this.gWidth+5)); 
        num=(num==0)?1:num;
        for (var i = 0; i < num; i++) {
            gEl=$('<div class="rtq-grid-bd-container"></div>').css({
                width: this.gWidth
            }).appendTo(this.body);
            grid=this._createGrid(gEl,this.gWidth,h,cols);
            grid.header.el.css('width',this.gWidth).appendTo(this.head);
            //grid.resize(this.gWidth,h);
            this.grids.push(grid);
            this.gridHeads.push(grid.header);
        }
        
//      if(num==gSize){
//          for(var i=0;i<gSize;i++){
//              this.grids[i].resize(this.gWidth,h);
//          }
//      }else if(num>gSize){
//          this.DOMMap={};
//          var hgSize=0,grid;
//          for (var i = gSize; i < num; i++) {
//              hgSize=this.hideGrids.length;
//              if(hgSize!=0&&this.hideGridHeads.length!=0){
//                  this.grids.push(this.hideGrids.pop());
//                  this.body.find('.rtq-grid-bd-container').eq(i).show();
//                  this.gridHeads.push(this.hideGridHeads.pop());
//                  this.gridHeads[i].el.show();
//              }else{
//                  gEl=$('<div class="rtq-grid-bd-container"></div>').css({
//                      width: this.gWidth
//                  }).appendTo(this.body);
//                  grid=this._createGrid(gEl,this.gWidth,h,cols);
//                  grid.header.el.css('width',this.gWidth).appendTo(this.head);
//                  grid.resize(this.gWidth,h);
//                  this.grids.push(grid);
//                  this.gridHeads.push(grid.header);
//              }
//          }
//      }else{
//          this.DOMMap={};
//          for(var i=gSize-1;i>=num;i--){
//              this._removeGrid(i);    
//          }
//          this.grids.splice(num,gSize-num);
//          this.gridHeads.splice(num,gSize-num);
//      }
    },
    _removeGrid:function(index){
        this.grids[index].empty();
        this.hideGrids.push(this.grids[index]);         
        this.body.find('.rtq-grid-bd-container').eq(index).hide();
        this.hideGridHeads.push(this.gridHeads[index]);
        this.gridHeads[index].el.hide();
    },
    _clearSelect:function(row){
        for(var i=0;i<this.grids.length;i++){
            if(!this.grids[i].rows[row.id]){
                this.grids[i]._clearSelect();   
            }
        }
    },
    _createGrid:function(container,w,h,cols){
        var self=this;
        var config={
            width:w,
            height:h,
            column:cols,
            outSideHeader:true,
            autoHeight:true
        };
        $.extend(this.config.gConfig,config);
        this.config.gConfig.headerContextMenu = false;//disable header contextmenu,David
        var grid=new Util.DataGrid(container,{},this.config.gConfig, {
            onRowSelected:function(e,row){
                self._clearSelect(row);
                self._trigger('rowselect',[e,row]);
            },
            onRowRemove:function(id,row){
                self.DOMMap[id]=null;
				self.rows[id]=null;
                self._trigger('rowremove',[id,row]);
            },
            onRowDragStart: function(e, proxy, row){
                self._trigger('rowdragstart',[e,proxy,row]);
            },
            onCellSort:function(cellKey, order){
                self.lastSortCellKey = cellKey;
                self._sortByCell(grid._id,cellKey, order);
            },
            onCellRearrange:function(cellKey,Index){
                self._appendColTo(grid._id,cellKey,Index);
            },
            onRowDoubleClick:function(e, row){
                self._trigger('rowdoubleclick',[e,row]);
            },
            onRowContextmenu:function(e,row){
                self._trigger('rowcontextmenu',[e,row]);
            },
            onGroupDragStart:function(proxy, group){
                var groupValue=group.value;
                for(var i=0;i<self.grids.length;i++){
                    if (self.grids[i].dataGroup.groups[groupValue]){
                        self.grids[i].dataGroup.groups[groupValue].el.addClass('rtq-grid-group-drag');
                    }
                }
            },
            beforeGroupDrop:function(proxy, group, toGroup){
                 proxy._stopEvent = true;
                 self._createData();
                 self._groupData();
                 var groupIndex=self.groupIndexMap[group.value];
                 var toGroupIndex=self.groupIndexMap[toGroup.value];



				 if(groupIndex<toGroupIndex){
                    toGroupIndex=toGroupIndex-1;//insert to before,to index need -1 
                 }
                 if(groupIndex==toGroupIndex){//if drag position is not changed.return
                    for(var i=0;i<self.grids.length;i++){
                        if (self.grids[i].dataGroup.groups[group.value]){
                            self.grids[i].dataGroup.groups[group.value].el.removeClass('rtq-grid-group-drag');
                        }
                    }
                    return;
                 }
                 var groupVal=self.groups[groupIndex];
                 self.groups.splice(groupIndex,1);
                 var beforeGroups=self.groups.slice(0,toGroupIndex);
                 var afterGroups=self.groups.slice(toGroupIndex,self.groups.length);
                 afterGroups.unshift(groupVal);
                 self.groups=beforeGroups.concat(afterGroups);
                 setTimeout(function(){
                     self._bindData();
                 }, 0);
            }
        });
        grid._id = 'grid'+self._newId();

        return grid;
    },  
    _trigger:function(event,args){
        var cb = null;
        switch (event.toLowerCase()) {
            case 'rowremove':
                cb = this.cb.onRowRemove;
            break;
            case 'rowdragstart':
                cb = this.cb.onRowDragStart;
            break;
            case 'cellsort':
                cb = this.cb.onCellSort;
            break;
            case 'cellrearrange':
                cb = this.cb.onCellRearrange;
            break;
            case 'rowdoubleclick':
                cb = this.cb.onRowDoubleClick;
            break;
            case 'rowcontextmenu':
                cb = this.cb.onRowContextmenu;
            break;
            case 'rowdragstart':
                cb = this.cb.onRowDragStart;
            break;
            case 'rowselect':
                cb = this.cb.onRowSelected;
            break;
            case 'scrollend':
                cb = this.cb.onScrollEnd;
            break;
            case 'afterbind':
                cb = this.cb.afterRebindData;
            break;
        }
        if(cb){
            cb.apply(this,args);
        }
    },
    _sortByCell:function(_id,cellKey, order){
        this._callbackCount["cellsort"]++;
        if(this._callbackCount["cellsort"]==1){
            for(var i=0;i<this.grids.length;i++){
                if(_id!=this.grids[i]._id){
                    this.grids[i].sortByCell(cellKey, order);
                }
            }
        }else if(this._callbackCount["cellsort"] == this.grids.length){
            this.sortByCell(cellKey, order);
        }
    },
    sortByCell:function(cellKey, order){
        //this.grids[0].sortByCell(cellKey,order);
        order = order || (this.grids[0].lastSortOrder == 'DESC'?'ASC':'DESC') || 'DESC';
        var isDESC = order.toUpperCase()=='DESC';
        //get dataType
        var type = 'string';
        for(var i=0;i<this.config.gColumns.length;i++){
            if(this.config.gColumns[i].dataIndex == cellKey){
                type = this.config.gColumns[i].dataType;
                break;
            }
        }
        //get data
        var data = [];
        for(var i in this.DOMMap){
            data.push(this._getData(i,this.rows[i]));
        }
        //sort data
        data.sort(function(row1, row2){
            var v1 = Util.DataGrid.prototype._dataTypeConvert(row1[cellKey], type);
            var v2 = Util.DataGrid.prototype._dataTypeConvert(row2[cellKey], type);
            switch (type) {
                case 'string':
                    break;
                default:
                    if (isNaN(v1)) {
                        return isDESC ? -1 : 1;
                    }
                    if (isNaN(v2)) {
                        return isDESC ? 1 : -1;
                    }
                    break;
            }
            if (v1 > v2) {
                return -1;
            }
            else 
                if (v1 == v2) {
                    return 0;
                }
                else {
                    return 1;
                }
        });
        if(isDESC){
            data.reverse();
        }
        
        this.reBindData(data);
        for (var i = 0; i < this.grids.length; i++) {
            this.grids[i]._clearSort();
            this.grids[i].lastSortCellKey = cellKey;
            this.grids[i].lastSortOrder = order.toUpperCase();
            if (order.toUpperCase() == 'ASC') {
                this.grids[i].header.row.cells[cellKey].el.addClass('rtq-grid-cell-sd');
            }
            else {
                this.grids[i].header.row.cells[cellKey].el.addClass('rtq-grid-cell-sa');
            }
        }
        
        this.lastSortCellKey = cellKey;
        this._trigger('cellsort',[cellKey, order]);
        this._callbackCount["cellsort"]=0;
    },
    _appendColTo:function(_id,cellKey,Index){
        this._callbackCount["cellrearrange"]++;
        if(this._callbackCount["cellrearrange"]==1){
            for(var i=0;i<this.grids.length;i++){
                if(_id!=this.grids[i]._id){
                    this.grids[i].appendColTo(cellKey, Index);
                }
            }
        }
		
		if(this._callbackCount["cellrearrange"] == this.grids.length){
            this._trigger('cellrearrange',[cellKey,Index]);
            this._callbackCount["cellrearrange"]=0;
        }
    },
    _resizeBody:function(w,h){
		var sw = w || this.body.width();
		var sh = h || this.body.height();
		if (this.config.fixHeight) {
			if (sw > 0 && sh > 0) {
				this.el.find('.rtq-multi-grid-scroll').css({
					width: sw,
					height: sh
				});
				this.scrollPanel.reSize(sw, sh);
			}
		}else{
			if (sw > 0 && sh > 0) {
                this.el.find('.rtq-multi-grid-scroll').css({
                    width: sw,
					height: 'auto'
                });
            }
		}
    },
    _groupData:function(){
        if(this.data==null||!this.data||this.data.length==0||!this.config.gConfig.groupDataIndex){
            return;
        }
        this.groupData={};
        this.groupIndexMap={};
        this.groups=[];
        var index=0;
        for(var i=0;i<this.data.length;i++){
            group=this.data[i][this.config.gConfig.groupDataIndex];
            group = typeof group == 'undefined' || group.length<1 ? Util.DG_emptyGroupKey : group;
            if(this.groupData[group]){
                this.groupData[group].push(this.data[i]);
            }else{
                this.groupData[group]=[];
                this.groupData[group].push(this.data[i]);
                this.groupIndexMap[group]=index;
                this.groups.push(group);
                index++;
            }
        }
    },
    _createData:function(){
        this.data=null;
        var ids=this.getIDs();
        this.data=[];
        var d,id;
        for(var i=0;i<ids.length;i++){
            d={};
            id=ids[i];
            if (this.config.gConfig.indexColKey){
                d[this.config.gConfig.indexColKey] = id;
            }
            var dataIndex;
            for (var j=0;j< this.config.gColumns.length;j++) {
                dataIndex=this.config.gColumns[j]["dataIndex"];
                d[dataIndex]=this.DOMMap[id][dataIndex].innerHTML;
            }
//			if(this.rows[id].data['InvalidTicker']){
//                d['InvalidTicker']=this.rows[id].data['InvalidTicker'];
//            }
			$.extend(true,d, this.rows[id].data);//extend other data from row.data
            this.data.push(d);
        }
    },
    _setGIndexMap:function(key,index){
        this.gIndexMap[key]=index;
    },
    _getMaxInArray:function(array){
        return Math.max.apply(Math,array); 
    },
    rearrangeData:function(data){
        if (data) {
            this.data = data;
        }
        else {
            this._createData();
        }
//      this._rearrangeData();
        this._groupData();
        this._bindData();
        this._resizeBody();
    },
    _rearrangeData:function(){
        if(!this.data){
            return;
        }
        if (this.config.gConfig.groupDataIndex) {
            this._arrangeGroupData();
        }else{
            this._arrangeData();
        }
        this.data=null;
    },
    _arrangeGroupData:function(){
//      var gSize=this.grids.length,
//          sumRows=this.data.length,//sum rows num
//          gRows=parseInt(sumRows/gSize),
//          rRows=sumRows%gSize,
//          tRows;//grid rows num
//      var data,lArray=[];
//      for(var i=0;i<gSize;i++){
//          if (rRows > i) {//distribute the remainder rows
//              tRows=gRows+1;
//          }else{
//              tRows=gRows;
//          }
//          data=this.data.splice(0,tRows);
//          this.grids[i].reBindData(data);
//          lArray.push(tRows+this.grids[i].dataGroup.length()*this.config.groupTitleRows);
//      }
//      var maxRows=this._getMaxInArray(lArray)+1;
//      for(var i=0;i<gSize;i++){
//          this.grids[i].resize(this.gWidth,maxRows*this.config.gRowsHeight);
//          for(var o in this.grids[i].DOMMap){
//              this.DOMMap[o]=this.grids[i].DOMMap[o];
//          }
//      }
//      this._resizeBody();
    },
    _arrangeData:function(){    
        var self=this;
        var gSize=this.grids.length;
        var lArray=[];
        if(gSize*this.maxAddRowsNum>=this.data.length){
            var data;
            for(var i=0;i<gSize;i++){
                data=this.data.splice(0,this.maxAddRowsNum);
                this.grids[i].reBindData(data);
                lArray.push(this.maxAddRowsNum);
            }
        }else{
            var data;
            var size=this.data.length;
            var pRows=parseInt(size/gSize);
            var rRows=size%gSize;
            var gRows=0;
            for (var i = 0; i < gSize; i++) {
                if (rRows > i) {//distribute the remainder rows
                    rows = pRows + 1;
                }
                else {
                    rows = pRows;
                }
                data=this.data.splice(0,rows);
                this.grids[i].reBindData(data);
                lArray.push(rows);
            }   
        }
        //var maxRows=this._getMaxInArray(lArray)+1;
        for(var i=0;i<gSize;i++){
            //this.grids[i].resize(this.gWidth,maxRows*this.config.gRowsHeight);
            for(var o in this.grids[i].DOMMap){
                this.DOMMap[o]=this.grids[i].DOMMap[o];
            }
			for(var id in this.grids[i].rows){
				this.rows[id]=this.grids[i].rows[id];
			}
        }
        this._resizeBody();
    },
    _getData:function(_id,row){
        var data={};
        var dataIndex;
        for (var j=0;j< this.config.gColumns.length;j++) {
            dataIndex=this.config.gColumns[j]["dataIndex"];
            data[dataIndex]=this.DOMMap[_id][dataIndex].textContent || this.DOMMap[_id][dataIndex].innerText;
        }
		if (row && row.data) {
			$.extend(data, row.data);
		}
        return data;
    },
    addRow:function(data,id,idx){
        var h=this.body.height();
//      for(var i=0;i<this.grids.length;i++){
//          this.grids[i].resize(this.gWidth,h);
//      }
        var g;
        if (this.config.gConfig.groupDataIndex) {
            g = data[this.config.gConfig.groupDataIndex];
            g = typeof g == 'undefined' || g.length<1 ? Util.DG_emptyGroupKey : g;
        }
        var flag=false; 
        if(idx==0){ 
            var index;
            if (g) {
                if (this.grids[0].dataGroup.groups[g] || typeof this.gIndexMap[g] == 'undefined') {
                    index = 0;
                }
                else {
                    index = this.gIndexMap[g];
                }
            }else{
                index=0;
            }
            this.grids[index].addRow(data,id,idx);
            if(g){
                this._setGIndexMap(g, index);
            }
            this.DOMMap[id] = this.grids[index].DOMMap[id];
			this.rows[id] = this.grids[index].rows[id];
            if(this.grids.length>1){
                for(var i=index;i<this.grids.length;i++){
                    var condition=this.grids[i].getRowLength()>this.maxAddRowsNum;
                    if(this.config.gConfig.groupDataIndex){
                        condition=(this.grids[i].getRowLength()+this.grids[i].dataGroup.length()*this.config.groupTitleRows)>this.maxAddRowsNum;
                    }
                    if(condition){
                        if (i != this.grids.length - 1) {
                            var _id = this.grids[i].getIDs()[this.grids[i].getRowLength() - 1];
                            var d = this._getData(_id,this.grids[i].rows[_id]);
                            this.grids[i + 1].addRow(d, _id, idx);                      
                            this.DOMMap[_id] ={};
                            this.DOMMap[_id] = this.grids[i + 1].DOMMap[_id];
							this.rows[_id] ={};
                            this.rows[_id] = this.grids[i + 1].rows[_id];
                            this.grids[i].removeRow(_id);
                            if (this.config.gConfig.groupDataIndex) {
                                var group = d[this.config.gConfig.groupDataIndex];
                                group = typeof group == 'undefined' || group.length<1 ? Util.DG_emptyGroupKey : group;
                                if (!this.grids[i].dataGroup.groups[group]) {
                                    this._setGIndexMap(group, i + 1);
                                }
                            }
                        }else{
                            flag=true;
                            break;
                        }
                    }else{
                        break;
                    }
                }
            }           
        }else{
            var index=this.gIndexMap[g];
            if (index >= 0) {
                this.grids[index].addRow(data, id, idx);
                this.DOMMap[id] = this.grids[index].DOMMap[id];
				this.rows[id] = this.grids[index].rows[id];
                if (this.grids.length > 1) {
                    var con;
                    
                    for (var i = index; i < this.grids.length; i++) {
                        con = this.grids[i].getRowLength() > this.maxAddRowsNum;
                        if (g) {
                            con = this.grids[i].getRowLength() + this.grids[i].dataGroup.length() * this.config.groupTitleRows > this.maxAddRowsNum;
                        }
                        if (con) {
                            if (i != this.grids.length - 1) {
                                var _id = this.grids[i].getIDs()[this.grids[i].getRowLength() - 1];
                                var d = this._getData(_id,this.grids[i].rows[_id]);
                                this.grids[i + 1].addRow(d, _id, 0);
                                this.DOMMap[_id] = {};
                                this.DOMMap[_id] = this.grids[i + 1].DOMMap[_id];
								this.rows[_id] ={};
                                this.rows[_id] = this.grids[i + 1].rows[_id];
                                this.grids[i].removeRow(_id);
                                if (this.config.gConfig.groupDataIndex) {
                                    var group = d[this.config.gConfig.groupDataIndex];
                                    group = typeof group == 'undefined' || group.length < 1 ? Util.DG_emptyGroupKey : group;
                                    if (this.grids[i].dataGroup.groups[group]) {
                                        this._setGIndexMap(group, i + 1);
                                    }
                                }
                            }
                            else {
                                flag = true;
                                break;
                            }
                        }
                        else {
                            break;
                        }
                    }
                }
            }
            else {  
                if (this.grids.length > 1) {
                    var condition;
                    
                    for (var i = 0; i < this.grids.length; i++) {
                        condition = this.grids[i].getRowLength() + 1 > this.maxAddRowsNum;
                        if (this.config.gConfig.groupDataIndex) {
                            var rows = this.grids[i].getRowLength() + 1 + (this.grids[i].dataGroup.length() + 1) * this.config.groupTitleRows;
                            condition = rows > this.maxAddRowsNum;
                        }
                        if (!condition) {
                            index = i;
                            break;
                        }
                    }
                }else{
                    index=0;
                }
                if (typeof index == 'undefined') {
                    index = this.grids.length - 1;
                    flag = true;
                }
                this.grids[index].addRow(data, id, idx);
                if (g) {
                    this._setGIndexMap(g, index);
                }
                this.DOMMap[id] = this.grids[index].DOMMap[id];
				this.rows[id] = this.grids[index].rows[id];
            }           
        }
        if(flag){
            Util.DelayRun('rearrange', this.rearrangeData, 0, this);
        }else{
            this._resizeBody();
            Util.DelayRun('removeGroupTitle', this._removeGroupTitle, 0, this);
        }       
    },
    _removeGroupTitle:function(){
        if (this.config.gConfig.groupDataIndex) {
            this._removeDuplicateGroup(0);
        }
    },
    _removeDuplicateGroup:function(index){
        var groups=this.grids[index].dataGroup.groups;
        if(index==this.grids.length-1||this.grids[index+1].getRowLength()==0){
            return;
        }
        var ids=this.grids[index].getIDs();
        var nextIds=this.grids[index+1].getIDs();
        if(this.DOMMap[ids[ids.length-1]][this.config.gConfig.groupDataIndex].innerHTML==this.DOMMap[nextIds[0]][this.config.gConfig.groupDataIndex].innerHTML){
            this.grids[index+1].el.find('.rtq-grid-group-til').eq(0).hide();
        }else{
            this.grids[index+1].el.find('.rtq-grid-group-til').eq(0).show();
        }
        if(index!=this.grids.length-2){
            this._removeDuplicateGroup(index+1);
        }
    },
    _bindData:function(){
        this.empty();
        var gSize=this.grids.length,
            group=this.config.gConfig.groupDataIndex,
            data;
        if (group) {
            data=this._splitGroupData(this.groupData,this.groups,this.maxAddRowsNum, gSize);
        }else{
            data=this._createGridsData(this.data, this.maxAddRowsNum,gSize);
        }
        if(data==null||data.length==0){
            return;
        }
        var gridData,hRows;
        for(var i=0;i<data.length;i++){
            gridData=this._getGridData(data[i]);
            this.grids[i].reBindData(gridData);
			             
            if(i-1>=0&&data[i][0][group]&&data[i-1][data[i-1].length-1][group]&&data[i][0][group]==data[i-1][data[i-1].length-1][group]){
                this.grids[i].el.find('.rtq-grid-group-til').eq(0).hide();
            }
//            if(this.config.gConfig.groupDataIndex){
//                hRows=gridData.length+this.grids[i].dataGroup.length()*this.config.groupTitleRows+1;
//            }else{
//                hRows=gridData.length+1;
//            }
            //this.grids[i].dataGroup
//          this.grids[i].resize(this.gWidth,this.config.gRowsHeight*hRows);
            for(var o in this.grids[i].DOMMap){
                this.DOMMap[o]=this.grids[i].DOMMap[o];
            }
			for(var id in this.grids[i].rows){
                this.rows[id]=this.grids[i].rows[id];
            }
        }
        this.groupData=null;
        this.data=null;
        this.groups=null;
        this.groupIndexMap=null;
    },
    reBindData:function(data){
        if(data) {
            this.data = data;
        }else{
            this._createData(); 
        }
        this._groupData();  
        this._bindData();   
        this._resizeBody();
        this._trigger('afterbind', [this.rows]);
    },
    _getGridData:function(data){
        var gridData=[];
        for(var i=0;i<data.length;i++){
            if(data[i]!='title'){
                gridData.push(data[i]);
            }
        }
        return gridData;
    },
    _splitGroupData:function(groupData,groups,maxRows,size){
        if (groupData==null) {
            return null;
        }else{
            //var groupData = this._groupData(this.data, this.config.gConfig.groupDataIndex);
            var d = [], tRows;
            if (this.config.groupAutoSort) {
                groups.sort();
            }
            tRows = Math.ceil(this.config.groupTitleRows);
//          if (tRows != this.config.groupTitleRows) {
//              tRows = tRows + 1;
//          }
            for(var i=0;i<groups.length;i++){
                var g=groupData[groups[i]];
                for (var r = 0; r < tRows; r++) {
                    d.push('title');
                }
                for (var j = 0; j < g.length; j++) {
                    d.push(g[j]);
                }
            }
            return this._createGridsData(d, this.maxAddRowsNum, size);
        }
    },
    _createGridsData:function(data,maxRows,size){
        var arr=[],a,rows;
        if (data.length <= maxRows * size&&this.config.fixHeight) {
			rows=maxRows;
        }else{
			rows=Math.ceil(data.length/size);
        }
		for (var i = 0; i < size; i++) {
            if(i!=size-1){
                a=data.slice(i*rows,rows*(i+1));
            }else{
                a=data.slice(rows*(size-1),data.length);
            }
			if(a.length!=0){
			   arr.push(a);	
			}
        }
        return arr;
    },
    _clearSort:function(grid){
        for(var i=0;i<this.grids.length;i++){
            if(this.grids[i]._id!=grid._id){
                this.grids[i]._clearSort();
            }
        }
    },
    _getGridIndexByGroup:function(groupBy){
        //after bind data ,we can know the grid
        if(this.gIndexMap[groupBy]!=undefined){
            return this.grids[this.gIndexMap[groupBy]]; 
        }
        return this.grids[0];
    },
    resize:function(w,h){
        if(w>0){this.el.width(w);this.head.width(w);}
        if(h>0){this.el.height(h);}
        this._createData();
        this._createMultiGrid(w, h-this.head.height(), this.config.gColumns);
        this._groupData();
        this._bindData();
        this._resizeBody();
    },
    getColumnCfg: function(){
        if (this.grids[0]) {
            return this.grids[0].cfg.column;
        }
        else {
            return this.config.gColumns;
        }
    },
    setColumnCfg:function(cols){
        this.config.gColumns = cols.slice();
        this._createMultiGrid(this.el.width(),this.el.height()-this.head.height(),this.config.gColumns);
        //this.body.empty();    
    },
    setGroup:function(group){
        if(group==null){
            this.groupSequence=[];
        }
        this.config.gConfig.groupDataIndex=group;
        for(var i=0;i<this.grids.length;i++){
            this.grids[i].setGroup(group);
        }   
    },
    getGroup:function(){
        return this.config.gConfig.groupDataIndex;
    },
    _getAllRowsDOM:function(){
        return this.body.find('.rtq-grid-row');
    },
    getIDs:function(){
        var a = [];
        var self = this;
        this._getAllRowsDOM().each(function(i){
            a.push(this.getAttribute('rowid'));
        });
        return a;
    },
    getRows:function(){
        var rows = {};
        for (var i = 0; i < this.grids.length; i++) {
            var r = this.grids[i].rows;
            for(var j in r){
                rows[j] = r[j];
            }
        }
        return rows;
    },
    getRowLength:function(){
        var i = 0;
        var rows = this.getRows();
        for(var r in rows){
            i++
        }
        return i;
    },
    getVisibleRow:function(scrollTop){
        var rows = {};
		if (this.config.fixHeight) {
			for (var i = 0; i < this.grids.length; i++) {
				var r = this.grids[i].getVisibleRow(scrollTop || this.scrollPanel.scrollTop, this.scrollPanel.el[0].offsetHeight, this.scrollPanel.el[0].offsetWidth);
				for (var j in r) {
					rows[j] = r[j];
				}
			}
		}else{
			$.extend(true,rows,this.rows);
		}
        return rows;
    },
    selectRow: function(rowid, e){
        for(var i=0;i<this.grids.length;i++){
            if(this.grids[i].rows[rowid]){
                this.grids[i].selectRow(rowid);
                break;
            }
        }
    },
    removeRow:function(id){
        for(var i=0;i<this.grids.length;i++){
            if(this.grids[i].rows[id]){
                this.grids[i].removeRow(id);
            }
        }
    },
    showLoading:function(){
    },
    hideLoading:function(){
    },
    empty:function(){
        for(var i=0;i<this.grids.length;i++){
            this.grids[i].empty();
        }
//      this.data=null;
//      this.grids=[];
//      this.gridHeads=[];
//      this.hideGrids=[];
//      this.hideGridHeads=[];
        this.DOMMap={};
		this.rows={};
        this.gIndexMap={};
//      this.body.empty();
//      this.head.empty();
        this._resizeBody();
    },
    clear:function(){
        this.el.empty();
        for (var p in this) {
            if (!p || p == 'clear') {
                continue;
            }
            this[p] = null;
            delete this[p];
        }
    },
	_newId:function(){
		return this._id--;
	}
};
